﻿using H.Configs;
using H.Daos;
using System;

namespace H.Config.Configs
{
    /// <summary>
    /// 配置实例工厂
    /// </summary>
    public class HConfigFactory : IConfigFactory
    {
        /// <summary>
        /// 存储已经打开的Dao实例,避免重复打开
        /// </summary>
        private WeakReference _Reference = null;

        ///<inheritdoc/>
        public IConfig CreateInstance(string configName)
        {
            IDao dao;

            if (_Reference == null || !_Reference.IsAlive)
            {
                IDaoFactory factory = IPlugin.GetObject<IDaoFactory>("H.Dao.SQLite");
                dao = factory.CreateInstance(HService.GetEnvPath(@"config\main.hdb"), null, false);
                _Reference = new WeakReference(dao);
            }
            else
            {
                dao = _Reference.Target as IDao;
            }

            return new HConfig(dao, configName);
        }
    }
}
